package com.anbinh.doctor.fragment.account;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.anbinh.doctor.DetailtActivity;
import com.anbinh.doctor.R;
import com.anbinh.doctor.adapter.ImagesAdapter;
import com.anbinh.doctor.model.DataResponse;
import com.anbinh.doctor.model.ImageData;
import com.anbinh.doctor.model.ResponseImage;
import com.anbinh.doctor.model.ResponseUploadImg;
import com.anbinh.doctor.model.UserLogin;
import com.anbinh.doctor.request.controller.ServerController;
import com.anbinh.doctor.service.request.OnRequest;
import com.anbinh.doctor.utils.Utils;
import com.lsjwzh.widget.materialloadingprogressbar.CircleProgressBar;
import com.mobeta.android.dslv.DragSortListView;

public class FragmentImages extends SherlockFragment {
	private static FragmentImages fragImages = null;
	private View mView;
	private CircleProgressBar loadding;
	private DragSortListView mListView;
	private ImagesAdapter adapter;
	private List<ImageData> mImagesList;
	private UserLogin user;
	private int mPosition;
	private UserLogin userLogin;

	public static FragmentImages newInstance() {
		if (fragImages == null)
			fragImages = new FragmentImages();
		return fragImages;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		pickFile(Utils.REQ_UPLOADIMG);
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data == null)
			return;
		FragmentImages.newInstance().updateInfo(data);
	}

	@Override
	public void onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu,
			com.actionbarsherlock.view.MenuInflater inflater) {
		menu.add(0, R.id.dia_diem_kham, Menu.NONE, "Thêm hình ảnh")
				.setIcon(R.drawable.ic_add)
				.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public void onResume() {
		super.onResume();
		((DetailtActivity) getActivity()).setActionBarTitle(getResources()
				.getString(R.string.them_hinh_anh));

	}

	public void pickFile(int requestCode) {
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("image/*");
		startActivityForResult(intent, requestCode);
	}

	private DragSortListView.DropListener onDrop = new DragSortListView.DropListener() {
		@Override
		public void drop(int from, int to) {
			ImageData item = adapter.getItem(from);

			adapter.notifyDataSetChanged();
			adapter.remove(item);
			adapter.insert(item, to);
			onChangePosition();

		}
	};

	private DragSortListView.RemoveListener onRemove = new DragSortListView.RemoveListener() {
		@Override
		public void remove(int which) {
			onDelete(adapter.getItem(which));
			adapter.remove(adapter.getItem(which));
		}
	};

	private DragSortListView.DragScrollProfile ssProfile = new DragSortListView.DragScrollProfile() {
		@Override
		public float getSpeed(float w, long t) {
			if (w > 0.8f) {
				// Traverse all views in a millisecond
				return ((float) adapter.getCount()) / 0.001f;
			} else {
				return 10.0f * w;
			}
		}
	};

	private String getListSpecial() {
		String result = "";
		for (int i = 0; i < adapter.getCount(); i++) {
			result = result + "," + adapter.getItem(i).getId();
		}

		return result.substring(1, result.length());
	}

	protected void onChangePosition() {
		ServerController.getInstance(getActivity()).requestChangePositionImg(
				userLogin.getData().getToken(), getListSpecial(),
				new OnRequest<DataResponse>() {

					@Override
					public void onSuccess(DataResponse data) {
					}

					@Override
					public void onError(int errorCode, String message) {
						loadding.setVisibility(View.INVISIBLE);
					}
				});
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		mListView = (DragSortListView) mView.findViewById(R.id.listDrag);
		mListView.setDropListener(onDrop);
		mListView.setRemoveListener(onRemove);
		mListView.setDragScrollProfile(ssProfile);

		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				mPosition = position;
				Bundle bundle = new Bundle();
				bundle.putInt(Utils.KEY, Utils.VIEW_IMG);
				bundle.putString(Utils.TITLE,
						getResources().getString(R.string.xem_anh));
				Utils.getNewIntent((Activity) getActivity(), bundle);
			}

		});
		mImagesList = new ArrayList<ImageData>();
		loadding = (CircleProgressBar) mView.findViewById(R.id.loadding);
		adapter = new ImagesAdapter(getActivity(), R.layout.item_image,
				mImagesList);
		mListView.setAdapter(adapter);
		onLoadListImg();
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		userLogin = Utils.getAccountModel(getActivity(), Utils.KEY_USER);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.warp_main, null);
		return mView;
	}

	public void onLoadListImg() {

		if (userLogin == null)
			return;
		loadding.setVisibility(View.VISIBLE);

		ServerController.getInstance(getActivity()).reuquestListImages(
				userLogin.getData().getToken(), new OnRequest<ResponseImage>() {

					@Override
					public void onSuccess(ResponseImage data) {
						loadding.setVisibility(View.INVISIBLE);
						if (getActivity() == null)
							return;

						if (data.getResponsecode() >= 0) {
							mImagesList.addAll(data.getData().getListItem());
							adapter.notifyDataSetChanged();
						}
					}

					@Override
					public void onError(int errorCode, String message) {
						loadding.setVisibility(View.INVISIBLE);

					}
				});
	}

	protected void onDelete(final ImageData item) {
		UserLogin userLogin = Utils.getAccountModel(getActivity(),
				Utils.KEY_USER);
		if (userLogin == null)
			return;
		ServerController.getInstance(getActivity()).requestdoRemoveImage(
				userLogin.getData().getToken(), item.getId(),
				new OnRequest<DataResponse>() {

					@Override
					public void onSuccess(DataResponse data) {
						if (getActivity() == null)
							return;

						Utils.showMessage(((Activity) getActivity()),
								data.getDescription());
					}

					@Override
					public void onError(int errorCode, String message) {

					}

				});
	}

	public int getmPosition() {
		return mPosition;
	}

	public void updateInfo(Intent data) {
		if (getActivity() == null)
			return;
		user = Utils.getAccountModel(getActivity(), Utils.KEY_USER);

		String token = user.getData().getToken();
		Uri selectedImage = data.getData();
		File file = new File(Utils.getRealPathFromURI(getActivity(),
				selectedImage));
		loadding.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, mView);
		ServerController.getInstance(getActivity()).requestUploadImg(token,
				file, new OnRequest<ResponseUploadImg>() {

					@Override
					public void onSuccess(ResponseUploadImg data) {
						if (getActivity() == null)
							return;

						loadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);
						if (data.getResponsecode() >= 0) {
							ImageData item = new ImageData();
							item.setThumb(data.getData().getImage());
							item.setImage(data.getData().getImage());
							item.setId(data.getData().getId());
							item.setUploader(user.getData().getUserInfo()
									.getFull_name());
							item.setCreated_at(Utils
									.getCurrentDayName("HH:mm:ss dd-MM-yyyy"));
							mImagesList.add(item);
							adapter.notifyDataSetChanged();
						}
						Utils.showMessage(getActivity(), data.getDescription());
					}

					@Override
					public void onError(int errorCode, String message) {
						loadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);
						Utils.showMessage(getActivity(), message);
					}
				});
	}

	public List<ImageData> getImagesList() {
		return mImagesList;
	}

	public void addNewImg(String thumb, int id) {

	}
}
